package com.shuohe.service.impl.system.user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shuohe.dao.system.user.DepartmentDao;
import com.shuohe.dao.system.user.UserDao;
import com.shuohe.entity.system.user.Department;
import com.shuohe.service.system.user.DepartmentService;
import com.shuohe.util.returnBean.ReturnBean;

@Service
public class DepartmentServiceImpl implements DepartmentService{

	@Autowired
	private DepartmentDao departmentDao;

	@Autowired
	private UserDao userDao;
	
	@Override
	public void save(Department department) {
		// TODO Auto-generated method stub
		departmentDao.save(department);
	}

	@Override
	public void delete(Department department) {
		// TODO Auto-generated method stub
		departmentDao.delete(department);
	}

	@Override
	public List<Department> getAll(int pid) {
		// TODO Auto-generated method stub
		List<Department> list = departmentDao.findAll();
		return getChildsManyGroup(list,pid);
	}
	/**
	 * 根据id返回所有子集分类,(多维List集合,List中含有子集List) 
	 * @author    秦晓宇
	 * @date      2017年1月10日 下午10:40:12 
	 * @param list
	 * @param pid
	 * @return
	 */
	public static List<Department> getChildsManyGroup(List<Department> list,int pid)
	{  
		List<Department> arr = new ArrayList<Department>();  
		for(Department location : list){  
		    if(pid == location.getParent_id()){  
		        location.setChildren(getChildsManyGroup(list, location.getId()));    
		        arr.add(location);   
		    }  
		}  
		return arr;  
	}

	@Override
	public Department getOne(int id) {
		// TODO Auto-generated method stub
		return departmentDao.findOne((long) id);
	}

	@Override
	public ReturnBean deleteDepartmentById(int id) {
		// TODO Auto-generated method stub
		//检查部门是否存在
		Department department = departmentDao.findById(id);
		if(department == null) return new ReturnBean(false,"该部门不存在");
		
		
		try {
			//删除部门
			departmentDao.deleteById(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnBean(false,"删除部门失败");
		}
		
		try {
			//将其下属部门放置于根目录下
			departmentDao.upDateDepartmentParentIdTo0(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnBean(false,"变更原下属部门到根目录下失败");
		}
		
		
		try {
			//将原部门下所有用户放置于根目录下
			userDao.upUserDepartmentIdTo0(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnBean(false,"变更原下属人员至根目录下失败");
		}
		
		
		return new ReturnBean(true,"删除部门成功") ;
	} 


}
